<?php
namespace app\admin\controller;
use app\common\controller\Admin;
use app\common\model\Notice as NoticeModel;
class Notice extends Admin{
   /**
    * 公告管理首页
    */
    public function index(){
        $where=[];
        $order='id desc';
        $this->assign('list', NoticeModel::getNoticeList($where,$order));
        $this->setMeta('公告管理');
        return $this->fetch('index');         
    }
    /**
     * 公告编辑
     */
    public function edit($id){
        $notice= model('notice');
        if ($this->request->isPost()) {
            $data=$this->request->param();
            if(empty($data['title'])||empty($data['url'])){
                 return $this->error('公告标题名称或者链接不能为空！');
            }
            if(strlen($data['title'])>300){
                return $this->error('公告标题不能超过100个字！');
            }
            $result =$notice->save($data, ['id' => $id]);
            if ($result !== false) {
                return $this->success("编辑成功", url('index'));
            } else {
                return $this->error($notice->getError());
            }
        } else {
            $info = db('notice')->where(array('id' => $id))->find();
            if (!$info) {
                return $this->error("非法操作！");
            }
            $data = array(
                'info' => $info,
                'keyList' => $notice->keyList,
            );
            $this->assign($data);
            $this->setMeta("公告编辑");
            return $this->fetch('public/edit');
        }
    }
    /**
     * 公告添加
     */
    public function add(){
         $notice= model('notice');
        if ($this->request->isPost()) {
            $data=$this->request->param();
            if(empty($data['title'])||empty($data['url'])){
                 return $this->error('公告标题名称或者链接不能为空！');
            }
            if(strlen($data['title'])>300){
                return $this->error('公告标题不能超过100个字！');
            }
            $result =$notice->save($data);
            if ($result !== false) {
                return $this->success("添加成功", url('index'));
            } else {
                return $this->error($notice->getError());
            }
        } else {
            $data = array(
                'keyList' => $notice->keyList,
            );
            $this->assign($data);
            $this->setMeta("新增公告");
            return $this->fetch('public/edit');
        }
    }
    /**
     * 公告删除
     */
    public function delete(){
        $notice= model('notice');
        $param = $this->request->param();
        $id = $param['id'];
        if (empty($id)) {
            return $this->error("非法操作！");
        }

        $map['id'] = array('IN', $id);
        $result =$notice->where($map)->delete();

        if (false !== $result) {
            //记录行为
            action_log('delete_notice', 'notice', $result, session('auth_user.uid'));
            return $this->success("删除成功！");
        } else {
            return $this->error("删除失败！");
        }
    }
}

